package com.backend.config;

import com.backend.interceptor.LoginInterceptor;
import com.backend.interceptor.RefreshTokenInterceptor;
import com.backend.interceptor.UserStatusInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {
    @Value("${frontend.host}")
    String host;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RefreshTokenInterceptor(stringRedisTemplate)).addPathPatterns("/**").order(0);
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns("/user/login", "/user/register", "/user/sendMail").order(1);
        registry.addInterceptor(new UserStatusInterceptor(stringRedisTemplate))
                .addPathPatterns("/**").order(2);
    }
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 允许所有路径跨域
                .allowedOrigins(host)  // 允许指定域名访问
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")  // 允许的HTTP方法
                .allowedHeaders("Content-Type", "Authorization")  // 允许的请求头
                .allowCredentials(true)  // 允许发送 Cookie（如果需要）
                .maxAge(3600);  // 预检请求缓存时间，单位秒
    }
}
